package com.google.jessewilson.codesearch.googlecodesearch;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import java.io.Reader;
import java.io.Writer;

/**
 * Strip the code from Google Code Search code snapshot page.
 *
 * <p>This uses a dangerously simple heuristic: We're within code if we've seen
 * an &lt;td width=100%&gt; and we're in a &lt;pre&gt; tag that has no attributes.
 *
 * @author jessewilson
 */
class FileDownloadHtmlToCode extends HtmlToCode {

  private boolean withinCode = false;
  private boolean seenTdWidth100 = false;
  private boolean preIsPlain = false;

  public FileDownloadHtmlToCode(Reader htmlIn, Writer codeOut) {
    super(htmlIn, codeOut);
  }

  @Override
  public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    super.startElement(uri, localName, qName, attributes);

    if ("td".equals(localName) && "100%".equals(attributes.getValue("width"))) {
      seenTdWidth100 = true;
    }
    if ("pre".equals(localName)) {
      preIsPlain = (attributes.getLength() == 0);
    }

    updateInCode();
  }

  @Override public void endElement(String uri, String localName, String qName) throws SAXException {
    super.endElement(uri, localName, qName);
    updateInCode();
  }

  /**
   * Reevaluate whether we're in the middle of a block of code.
   */
  private void updateInCode() {
    withinCode = seenTdWidth100 && tagStack.contains("pre") && preIsPlain;
  }

  @Override protected boolean withinCode() {
    return withinCode;
  }
}
